<?php

namespace app\home\controller;

use app\common\controller\Home;
use think\Env;

class Subject extends Home
{
    protected $noNeedLogin = ['detail', 'search', 'callback'];
    protected $PayModel = null;
    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->PayModel = model('Pay.Pay');
    }
    //课程详情页
    public function detail()
    {
        $subid = $this->request->param('subid', 0, 'trim');
        $info = $this->SubjectModel->find($subid);

        $LoginBusiness = session('LoginUser') ?? [];

        // 点赞状态
        $info['like_status'] = false;

        // 判断用户是否登陆
        if (!empty($LoginBusiness)) {
            $likes = !empty($info['likes']) ?  explode(',', $info['likes']) : [];
            if (count($likes) > 0) {
                if (in_array($LoginBusiness['id'], $likes)) {
                    $info['like_status'] = true;
                }
            }
        }
        $chapterlist = $this->ChapterModel->where('subid', $subid)->select();

        $info['chaptercount'] = count($chapterlist);
        $commentList = $this->CommentModel->with('business')->where('subid', $subid)->select();
        $this->assign([
            'info' => $info,
            'chapterlist' => $chapterlist,
            'commentList' => $commentList,

        ]);
        return $this->fetch();
    }
    // 搜索页面
    public function search()
    {
        if ($this->request->isPost()) {
            // 关键字
            $keywords = $this->request->param('keywords', '', 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $where = [];
            if (!empty($keywords)) {
                $where['title'] = ['like', "%$keywords%"];
            }
            $count = $this->SubjectModel->where($where)->count();
            // 分页查询 
            $subjectlist = $this->SubjectModel->with('category')->where($where)->page($page, $limit)->select();
            if ($subjectlist) {
                $this->success('', '', ['list' => $subjectlist, 'count' => $count]);
            } else {
                $this->error('暂无更多数据');
            }
        }
        $this->assign([
            'active2' => 'mui-active'
        ]);
        return $this->fetch();
    }
    // 订单页面
    public function order()
    {
        if ($this->request->isPost()) {
            // 关键字
            $keywords = $this->request->param('keywords', '', 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $where = ['busid' => $this->LoginUser['id']];
            if (!empty($keywords)) {
                $where['code|total|subject.title'] = ['like', "%$keywords%"];
            }
            $count = $this->OrderModel->with('subject')->where($where)->count();

            // 分页查询 
            $subjectlist = $this->OrderModel->with('subject')->where($where)->order('id', 'desc')->page($page, $limit)->select();
            foreach ($subjectlist as $item) {
                $res = $this->CommentModel->where(['busid' => $this->LoginUser['id'], 'subid' => $item['subid']])->find();
                if ($res) {
                    $item['comment_status'] = true;
                } else {
                    $item['comment_status'] = false;
                }
            }
            if ($subjectlist) {

                $this->success('', '', ['list' => $subjectlist, 'count' => $count]);
            } else {
                $this->error('暂无更多数据');
            }
        }

        return $this->fetch();
    }
    // 评价页面
    public function comment()
    {
        $subid = $this->request->param('subid', 0, 'trim');
        if ($this->request->isPost()) {
            $content = $this->request->param('content', '', 'trim');
            $data = [
                'subid' => $subid,
                'content' => $content,
                'busid' => $this->LoginUser['id']
            ];
            $reslut = $this->CommentModel->validate('common/Subject/Comment')->save($data);
            if ($reslut === false) {
                $this->error($this->CommentModel->getError());
            }
            $this->success('评价成功', 'home/business/index');
        }

        $info = $this->SubjectModel->find($subid);
        if (!$info) {
            $this->error('课程不存在', 'home/subject/order');
        }
        $this->assign([
            'info' => $info
        ]);
        return $this->fetch();
    }
    // 评价详情页面
    public function commentList()
    {
        $subid = $this->request->param('subid', 0, 'trim');

        if ($this->request->isPost()) {
            $keywords = $this->request->param('keywords', '', 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $where = ['subid' => $subid];
            if (!empty($keywords)) {
                $where['content'] = ['like', "%$keywords%"];
            }
            $count = $this->CommentModel->where($where)->count();
            $commentList = $this->CommentModel->with('business')->where($where)->page($page, $limit)->select();
            $this->success('', '', ['list' => $commentList, 'count' => $count]);
        } else {
        }
        $this->assign([
            'subid' => $subid
        ]);
        return $this->fetch();
    }
    // 点赞
    public function thumbsUp()
    {
        if ($this->request->isPost()) {
            $subid = $this->request->param('subid', 0, 'trim');
            $info = $this->SubjectModel->find($subid);
            if (!$info) {
                $this->error('课程不存在');
            }
            $likes = !empty($info['likes']) ?  explode(',', $info['likes']) : [];
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => '1'
            ];
            if (($key = array_search($this->LoginUser['id'], $likes)) !== false) {
                unset($likes[$key]);
                $result['msg'] = '取消点赞';
            } else {
                array_push($likes, $this->LoginUser['id']);
                $result['msg'] = '点赞';
            }
            $data = [
                'id' => $subid,
                'likes' => implode(",", $likes)
            ];
            $ret = $this->SubjectModel->isUpdate()->save($data);
            if ($ret) {
                $result['code'] = 1;
                $result['msg'] .= '成功';
            } else {
                $result['msg'] .= '失败';
            }
        }
        echo json_encode($result);
    }
    // 播放
    public function pay()
    {
        $subid = $this->request->param('subid', 0, 'trim');
        $chapterid = $this->request->param('chapterid', 0, 'trim');
        $info = $this->SubjectModel->find($subid);

        if (!$info) {
            $this->error('课程不存在');
        }

        $orderinfo = $this->OrderModel->where(['busid' => $this->LoginUser['id'], 'subid' => $subid])->find();

        if ($orderinfo) {
            $where = [];
            $where['subid'] = $subid;
            if ($chapterid != 0) {
                $where['id'] = $chapterid;
            }
            $chapterinfo = $this->ChapterModel->where($where)->find();
            if (!$chapterinfo['url']) {
                $this->success('暂无该课程视频', '', ['url' => '']);
            }
            $this->success('', '', $chapterinfo);
        } else {
            $this->error('请先购买该课程');
        }
    }
    // 购买课程
    public function buy()
    {
        $subid = $this->request->param('subid', 0, 'trim');
        $way = $this->request->param('way', 2, 'trim');
        $info = $this->SubjectModel->find($subid);
        if (!$info) {
            $this->error('课程不存在');
        }
        // 余额支付
        if ($way == 2) {
            // 判断用户余额
            $money = bcsub($this->LoginUser['money'], $info['price'], 2);
            if ($money < 0) {
                $this->error('余额不足，请充值');
            }
            $this->RecordModel->startTrans();
            $this->OrderModel->startTrans();
            $this->BusinessModel->startTrans();
            $orderDate = [
                'subid' => $subid,
                'busid' => $this->LoginUser['id'],
                'total' => $info['price'],
                'code' => build_code('USB')
            ];
            $recordDate = [
                'total' => $info['price'],
                'content' => '购买了[' . $info['title'] . ']课程,花费了￥' . $info['price'] . '元',
                'busid' => $this->LoginUser['id'],
                'state' => 1
            ];
            $orderReslut = $this->OrderModel->validate('common/Subject/Order')->save($orderDate);
            if ($orderReslut === false) {
                $this->error($this->OrderModel->getError());
            }
            $recordReslut = $this->RecordModel->validate('common/Business/Record')->save($recordDate);
            if ($recordReslut === false) {
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
            }
            $businessReslut = $this->BusinessModel->where('id', $this->LoginUser['id'])->update(['money' => $money]);
            if ($businessReslut === false) {
                $this->OrderModel->rollback();
                $this->RecordModel->rollback();
                $this->error('余额扣除失败');
            }
            $this->RecordModel->commit();
            $this->OrderModel->commit();
            $this->BusinessModel->commit();
            $this->success('购买成功！');
        } else {
            $money = floatval($info['price']);
            if ($money < 0) {
                $this->error('课程金额不能小于1元');
            }
            // 用户ID
            $third = json_encode(['busid' => $this->LoginUser['id'], 'subid' => $subid]);
            // Env 获取env文件路面的，没有再获取数据库里的 获取当前站点域名
            $url = Env::get('site.url', config('site.url'));
            // 下单地址
            $OrderUrl = $url . '/pay/index/create';
            $data = [
                'name' => $info['title'] . '课程购买',
                'third' => $third,
                'paytype' => $way,
                'originalprice' => $money,
                'paypage' => 1, // 0 json 1 收银页面,
                'reurl' => 'https://jie.jied.top/home/subject/notice',
                'callbackurl' => 'https://jie.jied.top/home/subject/callback',
                'status' => '0',
                'wxcode' => $url . config('site.wxcode'),
                'zfbcode' => $url . config('site.zfbcode'),
            ];
            $result = httpRequest($OrderUrl, $data);
            echo $result;
            exit;
        }
    }
    // 购买课程成功回调函数
    public function callback()
    {

        $params = $this->request->param();
        $price = isset($params['price']) ? $params['price'] : 0;

        $third = isset($params['third']) ? $params['third'] : '';
        // json字符串($third,true) true 转换数组 默认对象
        $third = json_decode($third, true);
        $subid = isset($third['subid']) ? $third['subid'] : 0;
        $busid = isset($third['busid']) ? $third['busid'] : 0;
        $paytype = isset($params['paytype']) ? $params['paytype'] : 0;
        // 支付订单id
        $payid = isset($params['id']) ? $params['id'] : 0;
        $pay = $this->PayModel->find($payid);

        if (!$pay) {
            return json(['code' => 0, 'msg' => '购买订单不存在', 'data' => null]);
        }
        // 充值类型转换
        $payment = '';
        switch ($paytype) {
            case 0:
                $payment = "微信支付";
                break;
            case 1:
                $payment = "支付宝支付";
                break;
        }

        // 判断充值金额
        if ($price <= 0) {
            return json(['code' => 0, 'msg' => '购买课程金额为0', 'data' => null]);
        }
        $this->RecordModel->startTrans();
        $this->OrderModel->startTrans();
        $info = $this->SubjectModel->find($subid);
        if (!$info) {
            $this->error('课程不存在');
        }
        $orderDate = [
            'subid' => $subid,
            'busid' => $busid,
            'total' => $price,
            'code' => build_code('USB')
        ];
        $recordDate = [
            'total' => $price,
            'content' => '使用' . $payment . '购买了[' . $info['title'] . ']课程,花费了￥' . $price . '元',
            'busid' => $busid,
            'state' => 1
        ];
        $orderReslut = $this->OrderModel->validate('common/Subject/Order')->save($orderDate);
        if ($orderReslut === false) {
            $this->error($this->OrderModel->getError());
        }
        $recordReslut = $this->RecordModel->validate('common/Business/Record')->save($recordDate);
        if ($recordReslut === false) {
            $this->OrderModel->rollback();
            $this->error($this->RecordModel->getError());
        }
        $this->RecordModel->commit();
        $this->OrderModel->commit();
        return json(['code' => 1, 'msg' => '购买成功', 'data' => null]);
    }
    //  购买课程完成后跳转的网页
    public function notice()
    {
        return $this->success('购买课程成功', '/home/business/record');
    }
}
